package com.zlm.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zlm.common.CustomException;
import com.zlm.common.Result;
import com.zlm.dto.DishDto;
import com.zlm.entity.Category;
import com.zlm.entity.Dish;
import com.zlm.entity.DishFlavor;
import com.zlm.service.CategoryService;
import com.zlm.service.DishFlavorService;
import com.zlm.service.DishService;
import com.zlm.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.zlm.utils.RedisConstants.DISH_STATUS_KEY;

/**
 * 菜品管理
 */

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private DishService dishService;

    // 这个引入因为我们要通过菜品标的categoryId来查询我们的category对应id的type
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        // 清理redis里面的缓存
        String key = DISH_STATUS_KEY + dishDto.getCategoryId() + "_1";
        stringRedisTemplate.delete(key);

        return dishService.saveWithFlavor(dishDto);
//        return null;

    }


    /**
     * 菜品信息分页
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page, int pageSize, String name) {
        // 构造分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> pageDto = new Page<>(page, pageSize);
        // 条件构造器
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        // 添加过滤条件(like进行模糊查询)
        lambdaQueryWrapper.like(name != null, Dish::getName, name);
        // 添加排序条件(根据更新时间来降序排序)
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);

        // 执行分页查询
        dishService.page(pageInfo, lambdaQueryWrapper);

        //对象拷贝(但是忽略了我们的数据)
        BeanUtil.copyProperties(pageInfo, pageDto, "records");

        List<Dish> dishRecords = pageInfo.getRecords();
        List<DishDto> dishDtoRecords = null;

        dishDtoRecords = dishRecords.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            // 因为你新创建了一个dto其他的属性就为空
            // 所以我们要进行拷贝
            BeanUtil.copyProperties(item, dishDto);

            // 得到每个菜品的分类id
            Long categoryId = item.getCategoryId();
            // 查询我们的分类的type
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();

            dishDto.setCategoryName(categoryName);


            return dishDto;

        }).collect(Collectors.toList());

        pageDto.setRecords(dishDtoRecords);

        return Result.success(pageDto);
    }


    /**
     * 回显数据的
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<DishDto> getByIdWithFlavor(@PathVariable("id") Long id) {

        return dishService.getByIdWithFlavor(id);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());

        // 精确菜品缓存数据
        //
        String key = DISH_STATUS_KEY + dishDto.getCategoryId() + "_1";
        stringRedisTemplate.delete(key);

        return dishService.updateWithFlavor(dishDto);
//        return null;

    }

    /**
     * 根据id修改我们售卖的状态
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public Result<String> updateStatus(@PathVariable("status") int status, Long[] ids) {


        List<Dish> dishes = dishService.listByIds(Arrays.asList(ids));
        for (Dish dish : dishes) {
            // 现根据我们的id查询到实体类
            // 精确菜品缓存数据
            //
            String key = DISH_STATUS_KEY + dish.getCategoryId() + "_1";
            stringRedisTemplate.delete(key);

            dish.setStatus(status);
            LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Dish::getId, dish.getId());
            dishService.update(dish, lambdaQueryWrapper);
        }

        /*for (Long id : ids) {

            Dish dish = dishService.getById(id);
            dish.setStatus(status);

            LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Dish::getId, id);
            dishService.update(dish, lambdaQueryWrapper);

        }*/


        return Result.success("修改成功");
    }

    /**
     * 对菜品进行删除 并且我们的口味也要删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping// 注意
    @Transactional
    public Result<String> deleteWithFlavor(String[] ids) {


        // 将里面全部需要删除取出来
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.in(Dish::getId, ids);
        dishLambdaQueryWrapper.eq(Dish::getStatus, 1);
        int count = (int) dishService.count(dishLambdaQueryWrapper);
        if (count > 0) {
            throw new CustomException("套餐正在售卖，不能删除");
        }

        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper1.in(Dish::getId, ids);
        dishService.remove(dishLambdaQueryWrapper1);
        // 删除口味的
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.in(DishFlavor::getDishId, ids);
        // dishFlavor是直接删除的
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);

        return Result.success("删除成功");

    }

    /**
     * 这个就是用来实现我们的新增套餐里面的每个菜类型有哪些菜
     *
     * @param dish
     * @return
     *//*
    @GetMapping("/list")
    public Result<List<Dish>> list(Dish dish) {
        // 构造查询条件对象
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 这个name就是那个搜索条件
        lambdaQueryWrapper.like(dish.getName() != null, Dish::getName, dish.getName());
        // 条件
        lambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        // 添加排序条件
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(lambdaQueryWrapper);
        return Result.success(list);
    }*/

    /**
     * 这个就是用来实现我们的新增套餐里面的每个菜类型有哪些菜
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public Result<List<DishDto>> list(Dish dish) {
        List<DishDto> listDto = null;

        String key = DISH_STATUS_KEY + dish.getCategoryId() + "_" + dish.getStatus();

        // 1.先从redis中获取数据
        String JsonStr = stringRedisTemplate.opsForValue().get(key);
        // 2.如果存在直接返回
        if (JsonStr != null) {
            List<DishDto> dishDtos = JSONUtil.toList(JsonStr, DishDto.class);
            return Result.success(dishDtos);
        }

        // 3.不存在查询数据库，在将查询到的数据缓存到redis里面

        // 构造查询条件对象
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 这个name就是那个搜索条件
        lambdaQueryWrapper.like(dish.getName() != null, Dish::getName, dish.getName());
        // 条件
        lambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());

        // 状态(停售的东西就不展示了)
        lambdaQueryWrapper.eq(Dish::getStatus, 1);
        // 添加排序条件
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(lambdaQueryWrapper);


        listDto = list.stream().map((item) -> {

            DishDto dishDto = new DishDto();

            // 因为你新创建了一个dto其他的属性就为空
            // 所以我们要进行拷贝  相当于里面又有item里面原有的数据
            BeanUtil.copyProperties(item, dishDto);

            // 得到每个菜品的分类id
            Long categoryId = item.getCategoryId();
            // 查询我们的分类的type
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();

            dishDto.setCategoryName(categoryName);


            // 得到我们的菜品的id
            Long dishId = item.getId();

            // 根据这个id来查询我们口味表
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(DishFlavor::getDishId, dishId);
            // 得到口味集合
            // sql: select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavors = dishFlavorService.list(lambdaQueryWrapper1);

            // set进去
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());

        // 现在就要存进我们的redis里面去(设置60分钟后过期)
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(listDto), 60, TimeUnit.MINUTES);

        return Result.success(listDto);
    }

}
